const exec = require('child_process').exec

const iconv = require('iconv-lite')
const fs = require('fs')

const encoding = 'cp936'
const binaryEncoding = 'binary'

export function cmdExec (cmd, isPrint = true) {
  return new Promise(function (resolve) {
    let resStr = ''
    const build = exec(cmd, { encoding: binaryEncoding })
    build.stdout.on('data', (data) => {
      let str = iconv.decode(Buffer.from(data, binaryEncoding), encoding)
      resStr += str
      isPrint && console.log(str)
    })
    build.stderr.on('data', (error) => {
      let str = iconv.decode(Buffer.from(error, binaryEncoding), encoding)
      resStr += str
      isPrint && console.error(str)
    })
    // build.on('end', () => {
    //   console.log('CMD end')
    //   resolve(resStr)
    // })

    build.on('close', () => {
      console.log('CMD close')
      resolve(resStr)
    })
  })
}

export async function deleteDirAndFile (dir) {
  if (!fs.existsSync(dir)) return
  await cmdExec(`rd /s /q ${dir}`)
}

export async function deleteFile (filePath) {
  if (!fs.existsSync(filePath)) return
  await cmdExec(`del /f /q "${filePath}"`)
}

/**
 * 打开文件夹或文件
 * @param path
 * @returns {Promise<void>}
 */
export async function openDirOrFile (path) {
  await cmdExec(`start "" "${path}"`)
}
